<template>
  <div class="purchase-detail">
    <el-dialog
      :title="detailData.title"
      v-model="detailData.dialogFormVisible"
      destroy-on-close
      width="520px"
    >
      <el-form
        class="content"
        :model="formData"
        :rules="formRules"
        ref="formDataRef"
        label-width="120px"
      >
        <el-form-item label="预算名称" prop="budgetName">
          <el-input
            class="text--info"
            v-model="formData.budgetName"
            placeholder="请输入预算名称"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="预算类型" prop="budgetTypeInfo">
          <el-select
            clearable
            filterable
            value-key="dicCode"
            placeholder="请选择预算类型"
            style="width: 100%"
            v-model="formData.budgetTypeInfo"
            @change="selectBudget"
          >
            <el-option
              v-for="item in budgetTypeList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="对应标段" prop="sectionInfo">
          <el-select
            clearable
            filterable
            placeholder="请选择项目标段"
            style="width: 100%"
            v-model="formData.sectionInfo"
            @change="selectSection"
          >
            <el-option
              v-for="item in sectionList"
              :label="item.sectionName"
              :key="item.id"
              :value="`${item.id},${item.sectionName}`"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="预算金额" prop="budgetAmount">
          <el-input
            class="text--info"
            v-model="formData.budgetAmount"
            placeholder="请输入预算金额"
          >
            <template #append>万元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="合同金额" prop="contractAmount">
          <el-input
            class="text--info"
            v-model="formData.contractAmount"
            placeholder="请输入合同金额"
          >
            <template #append>万元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="费率" prop="rate">
          <el-input
            class="text--info"
            v-model="formData.rate"
            placeholder="请输入费率"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-row justify="end" class="form__footer">
        <el-button @click="handleSubmit(false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit(true)">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import {
  addProjectBudget,
  updateProjectBudget,
  projectBudgetInfo
} from "/@/api/purchase";
// import { getSection } from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
export default defineComponent({
  name: "budgetDetail",
  props: {
    detailData: {
      type: Object,
      default: () => {}
    },
    budgetTypeList: {
      type: Array,
      default: () => []
    }
  },
  emits: ["emitClose", "updateClose"],
  setup(props, { emit }) {
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const projectList = ref([]);
    const sectionList = ref([]);
    const projrctInfo = storageLocal.getItem("projectInfo");
    let state = reactive({
      formData: {
        addMethod: "2",
        projectId: projrctInfo?.id,
        projectName: projrctInfo?.name,
        projectTypeCode: projrctInfo?.typeCode,
        projectTypeName: projrctInfo?.typeName,
        leaderId: projrctInfo?.leaderId,
        leaderName: projrctInfo?.leaderName,
        sectionInfo: "" as any,
        sectionId: "",
        sectionName: "",
        rate: "",
        contractAmount: "",
        budgetAmount: "",
        jcProjectId: "",
        jcProjectName: "",
        budgetName: "",
        budgetTypeInfo: "" as any,
        budgetTypeCode: "",
        budgetTypeName: ""
      }
    });
    const validateAmount = (rule: any, value: any, callback: any) => {
      if (!value) {
        if (rule.field === "budgetAmount") {
          return callback(new Error("请输入预算金额"));
        } else {
          callback();
        }
      } else {
        const reg = /^(([1-9]\d*)|0)(\.\d{1,5})?$/;
        if (!reg.test(value)) {
          if (rule.field === "rate") {
            return callback(new Error("请输入正确的费率"));
          } else {
            return callback(new Error("请输入正确的金额格式"));
          }
        } else {
          callback();
        }
      }
    };

    const formRules = ref({
      budgetName: [
        { required: true, message: "请输入预算名称", trigger: "blur" }
      ],
      budgetAmount: [
        { required: true, validator: validateAmount, trigger: "blur" }
      ],
      contractAmount: [{ validator: validateAmount, trigger: "blur" }],
      rate: [{ validator: validateAmount, trigger: "blur" }]
    });

    // 确认提交
    const handleSubmit = async (isSubmit: boolean) => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        if (String(props.detailData.id)) {
          updateBudget();
        } else {
          addBudget();
        }
      } else {
        emit("emitClose");
      }
    };

    //新增集采关联项目
    const addBudget = async () => {
      try {
        const { code, message } = await addProjectBudget(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    //更新集采关联项目
    const updateBudget = async () => {
      try {
        const { code, message } = await updateProjectBudget(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    // 获取详情
    const getBudgetInfo = async purId => {
      try {
        let postData = { id: purId };
        const { code, data } = await projectBudgetInfo(postData);
        if (code === 200) {
          state.formData = data;
          console.log(state.formData, "formDataformDataformData");
          state.formData.sectionInfo = data.sectionName;
          state.formData.budgetTypeInfo = {
            dicCode: data.budgetTypeCode,
            dicValue: data.budgetTypeName
          };
        }
      } catch (err) {
        console.log(err);
      }
    };

    //获取标段列表
    // const getSectionData = async () => {
    //   let obj = {
    //     projectId: projrctInfo?.id,
    //     pageNum: 1,
    //     pageSize: 500
    //   };
    //   try {
    //     const { code, data } = await getSection(obj);
    //     if (code === 200) {
    //       sectionList.value = data.list;
    //     }
    //   } catch (err) {
    //     console.log(err);
    //   }
    // };

    // 选择预算类型
    const selectBudget = async item => {
      state.formData.budgetTypeCode = item.dicCode;
      state.formData.budgetTypeName = item.dicValue;
    };

    // 选择标段
    const selectSection = async item => {
      const secArray = item.split(",");
      state.formData.sectionId = secArray[0];
      state.formData.sectionName = secArray[1];
    };

    if (String(props.detailData.id)) {
      getBudgetInfo(props.detailData.id);
    }
    // getSectionData()
    return {
      ...toRefs(state),
      handleSubmit,
      formRules,
      formDataRef,
      projectList,
      sectionList,
      selectSection,
      selectBudget
    };
  }
});
</script>
<style lang="scss" scoped>
:deep.purchase-detail {
  .content {
    padding-right: 46px;
  }
}
</style>
